package com.tianheng.wanzhou.datacollecting.netty.kyjR200;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianheng.wanzhou.datacollecting.db.entity.AirCompressorFun3;
import com.tianheng.wanzhou.datacollecting.db.entity.AirCompressorFun4;
import com.tianheng.wanzhou.datacollecting.db.entity.MachineList;
import com.tianheng.wanzhou.datacollecting.db.service.IAirCompressorFun3Service;
import com.tianheng.wanzhou.datacollecting.db.service.IAirCompressorFun4Service;
import com.tianheng.wanzhou.datacollecting.db.service.IMachineListService;
import com.tianheng.wanzhou.datacollecting.util.StrUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;


/**
 * @Author: yujw
 * @Date: 2020/5/12 14:26
 * @Version 1.0
 */
@Slf4j
@Component(value = "kongyajiR200Handler")
@Scope("prototype")
public class ClientHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    IAirCompressorFun3Service airCompressorFun3Service;

    @Autowired
    IAirCompressorFun4Service airCompressorFun4Service;

    @Autowired
    IMachineListService machineListService;
    private List<MachineList> machineList = new ArrayList<>();

//    @Resource
//    Jedis jedis;

    private static ClientHandler clientHandler;

    @PostConstruct
    public void init() {
        clientHandler = this;
        airCompressorFun3Service = this.airCompressorFun3Service;
        airCompressorFun4Service = this.airCompressorFun4Service;
        QueryWrapper<MachineList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mac_type", 2).eq("status", 1).eq("son_type", "01");
        machineList = machineListService.list(queryWrapper);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx){
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        log.info("连接服务端" + clientIP + "成功!");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        try {
            MachineList machine = new MachineList();
            for (MachineList machine1 : this.machineList) {
                if(clientIP.equals(machine1.getMacIp())){
                    machine =machine1;
                    break;
                }
            }
            ByteBuf buf = (ByteBuf)msg;
            byte[] bytes = new byte[buf.readableBytes()];
            buf.readBytes(bytes);
            String str = StrUtil.bytesToHexString(bytes);
            log.info("收到数据:" + str);
            String data = str.substring(6, str.length() - 4);
            AirCompressorFun3 airCompressorFun3 = new AirCompressorFun3();
            AirCompressorFun4 airCompressorFun4 = new AirCompressorFun4();



            if (str.substring(2,6).equals("0304")){
                airCompressorFun3.setCompanyId(machine.getCompany());
                airCompressorFun3.setMachineIp(machine.getMacIp());
                airCompressorFun3.setMachineId(machine.getMacId());
                airCompressorFun3.setValvePosition(StrUtil.hexStr2Int(data.substring(0,4)));
                airCompressorFun3.setUnloadingValvePosition(StrUtil.hexStr2Int(data.substring(4,8)));
                airCompressorFun3Service.saveOrUpdate(airCompressorFun3);
            }
            if (str.substring(2, 6).equals("044C")) {
                airCompressorFun4.setCompanyId(machine.getCompany());
                airCompressorFun4.setMachineIp(machine.getMacIp());
                airCompressorFun4.setMachineId(machine.getMacId());
                airCompressorFun4.setWorkshopId(machine.getWorkshop());
                airCompressorFun4.setDpt(StrUtil.hexStr2Int(data.substring(0 , 4)).doubleValue()/715);
                airCompressorFun4.setOpt(StrUtil.hexStr2Int(data.substring(4 , 8)).doubleValue()/1450);
                airCompressorFun4.setMat(StrUtil.hexStr2Int(data.substring(8 , 12)).doubleValue()/50);
                airCompressorFun4.setLvt(StrUtil.hexStr2Int(data.substring(12 , 16)).doubleValue()/100);
                airCompressorFun4.setHvt(StrUtil.hexStr2Int(data.substring(16 , 20)).doubleValue()/100);
                airCompressorFun4.setIot(StrUtil.hexStr2Int(data.substring(20 , 24)).doubleValue()/50);
                airCompressorFun4.setIat(StrUtil.hexStr2Int(data.substring(24 , 28)).doubleValue()/60);
                airCompressorFun4.setSpt(StrUtil.hexStr2Int(data.substring(36,40)).doubleValue());
                airCompressorFun4.setOmt(StrUtil.hexStr2Int(data.substring(40,44)));
                airCompressorFun4.setSMt1(StrUtil.hexStr2Int(data.substring(44,48)));
                airCompressorFun4.setImt(StrUtil.hexStr2Int(data.substring(48,52)));
                airCompressorFun4.setAct(StrUtil.hexStr2Int(data.substring(52,56)));
                airCompressorFun4.setAfdp(StrUtil.hexStr2Int(data.substring(56,60)));
                airCompressorFun4.setOftofdt(StrUtil.hexStr2Int(data.substring(60,64)));
                airCompressorFun4.setFdt(StrUtil.hexStr2Int(data.substring(84,88)));
                airCompressorFun4.setSdt(StrUtil.hexStr2Int(data.substring(88,92)));
                airCompressorFun4.setFit(StrUtil.hexStr2Int(data.substring(92,96)));
                airCompressorFun4.setUDt1HVT2(StrUtil.hexStr2Int(data.substring(148,152)));
                airCompressorFun4Service.saveOrUpdate(airCompressorFun4);
                ctx.channel().close();
                ctx.close();

            }

//            if (str.substring(2, 6).equals("044C")) {
//                ctx.channel().close();
//                ctx.close();
//            }
        }finally {
            ReferenceCountUtil.release(msg);
        }

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx){
        log.info("数据读取完毕");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx){
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        log.info("连接"+ clientIP +"移除");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("发生错误:" + cause.toString());
        ctx.close();
    }

}
